package com.spongebob.controller.wz;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spongebob.dao.WorkOrderMapper;
import com.spongebob.pojo.CustomerService;
import com.spongebob.pojo.WorkOrder;
import com.spongebob.pojo.WorkOrderReply;
import com.spongebob.service.CustomerServiceService;
import com.spongebob.service.WorkOrderReplyService;
import com.spongebob.service.WorkOrderService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 工作订单 前端控制器
 * </p>
 *
 * @author tutu
 * @since 2021-03-16
 */
@Controller
public class WorkOrderController {
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private CustomerServiceService customerServiceService;
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private WorkOrderReplyService workOrderReplyService;

    /**
     * 分页进入
     *
     * @param model
     * @param session
     * @param pn
     * @return
     */
    @RequestMapping("/orderManager")
    public String orderManager(Model model, HttpSession session, @RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "order", defaultValue = "null") String order) {
        model.addAttribute("status", 6);
        System.out.println("刚进入页面的order值为：---" + order);
        QueryWrapper qw = new QueryWrapper();
        //session的初始值判断
        if (order.equals("createtime")) {
            session.setAttribute("orders", "createtime");
        } else if (order.equals("updatetime")) {
            session.setAttribute("orders", "updatetime");
        } else if (order.equals("未分配")) {
            session.setAttribute("orders", "未分配");
        } else if (order.equals("紧急")) {
            session.setAttribute("orders", "紧急");
        } else if (order.equals("高")) {
            session.setAttribute("orders", "高");
        } else {
            session.setAttribute("orders", "null");
            System.out.println("现在是翻页中");
            System.out.println("进入下一页----" + pn.toString());
        }


        //排序赋值
        if (session.getAttribute("orders").equals("createtime")) {
            order = "createtime";
            System.out.println("创建时间排序---翻页的下一页");
        } else if (session.getAttribute("orders").equals("updatetime")) {
            order = "updatetime";
        } else if (session.getAttribute("orders").equals("未分配")) {
            order = "未分配";
        } else if (session.getAttribute("orders").equals("紧急")) {
            order = "紧急";
        } else if (session.getAttribute("orders").equals("高")) {
            order = "高";
        } else if (session.getAttribute("orders").equals("中")) {
            order = "中";
        } else if (session.getAttribute("orders").equals("低")) {
            order = "低";
        }

        System.out.println("确定方式是" + order);

        if (order.equals("未分配")) {
            qw.eq("state", order);
        } else if (order.equals("紧急") || order.equals("高") || order.equals("中") || order.equals("低")) {
            qw.eq("priority", order);
        } else {
            qw.orderByDesc(order);
        }


        QueryWrapper qw2 = new QueryWrapper();
        List<WorkOrderReply> wreply = workOrderReplyService.list();
        model.addAttribute("wreply", wreply);
        Page<WorkOrder> page = new Page<>(pn, 8);
        Page<WorkOrder> page1 = workOrderService.page(page, qw);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", order);
        System.out.println("工单controller页进入");
        model.addAttribute("status", 6);

        return "index";
    }


    //搜索
    @RequestMapping(value = "/orderManager/search", method = RequestMethod.GET)
    public String searchWorkOrder(@RequestParam("title") String title, Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {

        System.out.println("搜索啊啊啊---------------------");

        QueryWrapper qw2 = new QueryWrapper();
        List<WorkOrderReply> wreply = workOrderReplyService.list();
        model.addAttribute("wreply", wreply);
        QueryWrapper<WorkOrder> qu = new QueryWrapper<>();
        qu.like("title", title);
        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qu);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "all");
        model.addAttribute("status", 6);
        return "index";
    }

    /**
     * 单个删除
     *
     * @param id
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/orderManager/del")
    public String workorderdel(@RequestParam("workid") int id, Model model, HttpSession session) {
        System.out.println("删除id为" + id + "的行");
        workOrderService.removeById(id);
        System.out.println("删除成功");
        return "redirect:/orderManager";
    }

    /**
     * 添加工单
     *
     * @return
     */
    @RequestMapping(value = "/orderManager/workorderadd", method = RequestMethod.POST)
    public String workorderadd(WorkOrder workOrder) {
        workOrder.setCreatetime(new Date());
        workOrder.setUpdatetime(new Date());
        workOrder.setState("待处理");
        workOrder.setDeleted(0);
        workOrderService.save(workOrder);
        return "forward:/orderManager";
    }


    @RequestMapping("/orderManageras")
    public String workodc(HttpSession session) {
        System.out.println("工单controller页进入");
        session.setAttribute("status", 6);
        return "index";
    }

    /**
     * 批量删除
     *
     * @param list
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/orderManager/muldel")
    public String workrdermuldel(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        for (String s : ids) {
            System.out.println("s " + s);
            workOrderService.removeById(s);
        }


        return "redirect:/orderManager";
    }

    /**
     * 紧急程度-----标记为紧急
     *
     * @param list
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/orderManager/starjinji")
    public String workorderstaijinji(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("标记为紧急");
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setPriority("紧急");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为高优先级
     */
    @RequestMapping("/orderManager/stargyxj")
    public String stargyxj(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setPriority("高");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为中优先级
     */
    @RequestMapping("/orderManager/starzyxj")
    public String starzyxj(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setPriority("中");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为低优先级
     */
    @RequestMapping("/orderManager/stardyxj")
    public String stardyxj(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setPriority("低");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为已完成
     */
    @RequestMapping("/orderManager/starywc")
    public String starywc(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setState("已解决");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为已关闭
     */
    @RequestMapping("/orderManager/starygb")
    public String starygb(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setState("已关闭");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为已未分配
     */
    @RequestMapping("/orderManager/starwfp")
    public String starwfp(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setState("未分配");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为处理中
     */
    @RequestMapping("/orderManager/starclz")
    public String starclz(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        System.out.println("处理中");
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setState("处理中");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 标记为待处理
     */
    @RequestMapping("/orderManager/stardcl")
    public String stardcl(@RequestParam("list") String list, Model model, HttpSession session) {
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();
        ArrayList<WorkOrder> w = new ArrayList();
        for (String s : ids) {
            WorkOrder w1 = new WorkOrder();
            System.out.println("s " + s);

            w1.setId(Integer.decode(s));
            w1.setState("待处理");
            w.add(w1);

        }
        workOrderService.updateBatchById(w);
        return "redirect:/orderManager";
    }

    /**
     * 创建时间排序
     *
     * @param model
     * @return
     */
    @RequestMapping("/workorder/creattime")
    public String workordertime1(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {


        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("createtime");

        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qw);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "all");


        System.out.println("创建时间排序------工单controller页进入");
        session.setAttribute("status", 6);

        return "index";
    }

    /**
     * 更新时间排序
     *
     * @param model
     * @return
     */
    @RequestMapping("/workorder/uptime")
    public String workordertime2(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("updatetime");

        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qw);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "all");


        System.out.println("更新时间排序------工单controller页进入");
        session.setAttribute("status", 6);

        return "index";
    }

    /**
     * 排序 通过未分配
     */
    @RequestMapping("/workorder/vstate")
    public String vstate(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {

        QueryWrapper qw = new QueryWrapper();
        qw.eq("state", "未分配");

        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qw);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "all");

        System.out.println("未分配排序------工单controller页进入");
        session.setAttribute("status", 6);

        return "index";
    }


    /**
     * 批量下载功能
     *
     * @param list
     * @param model
     * @param session
     * @param response
     * @throws IOException
     */
    @RequestMapping("/orderManager/voutputworkorder")
    public void workorderoutput(@RequestParam("list") String list,
                                Model model,
                                HttpSession session,
                                HttpServletResponse response) throws IOException {
        System.out.println("下载");
        System.out.println("list  " + list);
        String[] ids = list.split(",");
        QueryWrapper qw = new QueryWrapper();

        System.out.println("进入下载");
        List<WorkOrder> workOrders = workOrderMapper.selectBatchIds(Arrays.asList(ids));
        System.out.println(workOrders);
        System.out.printf("------------" + workOrders.toString());
        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFSheet sheet = wb.createSheet("获取excel测试表格");

        HSSFRow row = null;

        row = sheet.createRow(0);//创建第一个单元格
        row.setHeight((short) (26.25 * 20));
        row.createCell(0).setCellValue("工单信息列表");//为第一行单元格设值

        /*为标题设计空间
         * firstRow从第1行开始
         * lastRow从第0行结束
         *
         *从第1个单元格开始
         * 从第3个单元格结束
         */
        CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
        sheet.addMergedRegion(rowRegion);
        sheet.setColumnWidth(0, 3000);
      /*CellRangeAddress columnRegion = new CellRangeAddress(1,4,0,0);
      sheet.addMergedRegion(columnRegion);*/

        row = sheet.createRow(1);
        row.setHeight((short) (22.50 * 20));//设置行高
        row.createCell(0).setCellValue("id");//为第一个单元格设值
        row.createCell(1).setCellValue("工单类型");//为第二个单元格设值
        row.createCell(2).setCellValue("标题");//为第三个单元格设值
        row.createCell(3).setCellValue("工单描述");//为第四个单元格设值
        row.createCell(4).setCellValue("附件");//为第四个单元格设值
        row.createCell(5).setCellValue("客服");//为第四个单元格设值
        row.createCell(6).setCellValue("优先级");//为第四个单元格设值
        row.createCell(7).setCellValue("状态");//为第四个单元格设值
        row.createCell(8).setCellValue("客服组id");//为第四个单元格设值
        row.createCell(9).setCellValue("客户id");//为第四个单元格设值
        row.createCell(10).setCellValue("渠道");//为第四个单元格设值


        row.createCell(11).setCellValue("更新时间");//为第四个单元格设值
        row.createCell(12).setCellValue("创建时间");//为第四个单元格设值

        //遍历所获取的数据
        for (int i = 0; i < workOrders.size(); i++) {
            row = sheet.createRow(i + 2);
            WorkOrder visitorInfo = workOrders.get(i);
            row.createCell(0).setCellValue(visitorInfo.getId());
            row.createCell(1).setCellValue(visitorInfo.getTitle());
            row.createCell(2).setCellValue(visitorInfo.getOrderdesc());
            row.createCell(3).setCellValue(visitorInfo.getAttachments());
            row.createCell(4).setCellValue(visitorInfo.getCclist());
            row.createCell(5).setCellValue(visitorInfo.getPriority());
            row.createCell(6).setCellValue(visitorInfo.getState());
            row.createCell(7).setCellValue(visitorInfo.getCustomerservicegroupid());
            row.createCell(8).setCellValue(visitorInfo.getCustomerserviceid());
            row.createCell(9).setCellValue(visitorInfo.getCustomerid());
            row.createCell(10).setCellValue(visitorInfo.getChannel());



            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String vtime= sdf.format(visitorInfo.getCreatetime());

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String vtime2= sdf.format(visitorInfo.getUpdatetime());
            row.createCell(11).setCellValue(vtime);

            row.createCell(12).setCellValue(vtime2);
        }
        sheet.setDefaultRowHeight((short) (16.5 * 20));
        //列宽自适应
        for (int i = 0; i <= 13; i++) {
            sheet.autoSizeColumn(i);
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment;filename=workorderinfo.xls");//默认Excel名称
        wb.write(os);
        os.flush();
        os.close();

    }


    /**
     * 上侧边栏
     *
     * @param model
     * @param pn
     * @param session
     * @return
     */

    @RequestMapping("/orderManager/myWillSolved")
    String myWillSolved(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        CustomerService cs = (CustomerService) session.getAttribute("user");
        String username = cs.getEmail();
        QueryWrapper<CustomerService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", username);
        CustomerService customerService = customerServiceService.getOne(queryWrapper);
        Integer customerServiceId = customerService.getCustomerserviceid();

        QueryWrapper<WorkOrder> qu = new QueryWrapper<>();
        qu.eq("customerServiceId", customerServiceId);
        qu.eq("state", "待处理");
        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qu);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "myWillSolved");
        model.addAttribute("status", 6);
        return "index";
    }

    @RequestMapping("/orderManager/mySolved")
    String mySolved(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        CustomerService cs = (CustomerService) session.getAttribute("user");
        String username = cs.getEmail();
        QueryWrapper<CustomerService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", username);
        CustomerService customerService = customerServiceService.getOne(queryWrapper);
        Integer customerServiceId = customerService.getCustomerserviceid();

        QueryWrapper<WorkOrder> qu = new QueryWrapper<>();
        qu.eq("customerServiceId", customerServiceId);
        qu.eq("state", "已解决");
        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qu);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "mySolved");
        model.addAttribute("status", 6);
        return "index";
    }

    @RequestMapping("/orderManager/myProcessed")
    String myProcessed(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        CustomerService cs = (CustomerService) session.getAttribute("user");
        String username = cs.getEmail();
        QueryWrapper<CustomerService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", username);
        CustomerService customerService = customerServiceService.getOne(queryWrapper);
        Integer customerServiceId = customerService.getCustomerserviceid();

        QueryWrapper<WorkOrder> qu = new QueryWrapper<>();
        qu.eq("customerServiceId", customerServiceId);
        qu.eq("state", "处理中");
        Page<WorkOrder> page = new Page<>(pn, 7);
        Page<WorkOrder> page1 = workOrderService.page(page, qu);
        List<WorkOrder> lists = page1.getRecords();
        model.addAttribute("page", page1);
        model.addAttribute("list", lists);
        model.addAttribute("activeUri", "myProcessed");
        model.addAttribute("status", 6);
        return "index";
    }


    /**
     * 修改工单信息
     */


    @RequestMapping(value = "/orderManager/update", method = RequestMethod.POST)
    public String updateWorkOrder(WorkOrder workOrder) {
        System.out.println("更新----------------" + workOrder.getId());
        workOrder.setUpdatetime(new Date());

        System.out.println(workOrder);

        workOrderService.updateById(workOrder);
        return "redirect:/orderManager";
    }

}

